package com.knight.admin.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;

import com.alibaba.druid.support.json.JSONUtils;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.knight.admin.common.constant.Constant;
import com.knight.admin.model.Content;
import com.knight.admin.model.Menu;
import com.knight.admin.response.JsonMessage;
import com.knight.admin.service.MenuService;
import com.knight.admin.service.NewsService;
import com.knight.admin.utils.FileUtils;

public class NewsManagerController extends Controller {

	private static final Logger logger = Logger.getLogger(NewsManagerController.class);

	/**
	 * 图片上传目录
	 */
	private static final String UPLOAD_IMAGE_DIRECTORY = Constant.ACCESS_IMAGE_PRE+"new" + File.separator;

	private static MenuService menuService = MenuService.getInstance();
	private static NewsService newsService = NewsService.getInstance();

	public void list() {

		List<Menu> list = menuService.findMenuByparentId(Constant.MenuTypes.LEVEL_TWO_MENU,
				Constant.ParentMenuId.NEWS_ID);

		Content model = getModel(Content.class);
		String menuId = "";
		if (model.getType() != null && !"".equals(model.getType())) {
			menuId = model.getType();
		} else {
			menuId = list.get(0).getId();
		}

		Page<Content> contents = newsService.queryContents(getParaToInt("pageIndex", 1), 5, menuId);
		setAttr("childMenus", list);
		setAttr("contents", contents);
		setAttr("currentMenuId", menuId);
		render("news/list.html");
	}

	public void detail() {
		setAttr("title", "动态详情");
		List<Menu> list = menuService.findMenuByparentId(Constant.MenuTypes.LEVEL_TWO_MENU,
				Constant.ParentMenuId.NEWS_ID);
		setAttr("childMenus", list);
		Content content = newsService.findById(getParaToInt(0, 1));
		setAttr("c", content);
		render("news/detail.html");
	}

	/**
	 * 保存或编辑
	 */
	public void addOrEdit() {
		Content content = getModel(Content.class);
		String dynamicContent = getPara("content");
		newsService.saveOrUpdate(content, dynamicContent);
		redirect("/news/list");
	}

	/**
	 * 跳转到添加页面
	 */
	public void addPage() {
		List<Menu> list = menuService.findMenuByparentId(Constant.MenuTypes.LEVEL_TWO_MENU,
				Constant.ParentMenuId.NEWS_ID);
		setAttr("childMenus", list);
		setAttr("title", "添加动态");
		render("news/add.html");
	}

	public void deleteContent() {
		Integer id = getParaToInt(0, 1);

		Content content = newsService.findById(id);
		if (content != null) {
			String content2 = content.getContent();// html文件内容
			if (StringUtils.isNoneBlank(content2)) {
				if (content2.contains("<img")) {
					logger.debug("-------start delete image-------");
					// 只有上传图片的才需要删除
					List<String> imgSrcs = FileUtils.getImgSrc(content2);
					if (imgSrcs != null && !imgSrcs.isEmpty()) {
						for (String imgSrc : imgSrcs) {
							FileUtils.deleteFile(imgSrc);
						}
					}

					logger.debug("-------end delete image-------");

				}
			}
		}

		boolean flag = newsService.delete(id);
		JsonMessage message = new JsonMessage();
		if (flag) {
			message.setSuccess("0");
			message.setSuccMessage("删除成功");
		} else {
			message.setSuccess("1");
			message.setErrorMessage("删除失败");
		}

		renderJson(message);
	}

	/**
	 * 上传文件方法
	 */
	public void uploadFile() {

		String uploadPath = UPLOAD_IMAGE_DIRECTORY + DateFormatUtils.format(new Date(), "yyyyMMdd");
		UploadFile uploadFile = this.getFile("upfile", uploadPath);
		Map<String, Object> jsonMap = new HashMap<>();
		jsonMap.put("error", "0");
		ArrayList<String> strings = new ArrayList<>();
		strings.add(uploadPath + File.separator + uploadFile.getFileName());
		jsonMap.put("data", strings);

		String result = JSONUtils.toJSONString(jsonMap);

		renderJson(result);
	}

}
